﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(BoxCollider))]
public class MyTouch : MonoBehaviour
{
    [NonSerialized]
    public Touch touch;

    public bool isInUpdate = false;

    [NonSerialized]
    public bool isTouch = false;

    public event Action onClick;
    public event Action onDown;
    public event Action onUp;
    private short touchTimeout = 0;

    void Start()
    {
        GameAdManager.NewScene();
    }

    void Update()
    {
        if (isInUpdate)
        {
            touchTimeout = 0;
            isInUpdate = false;
            if (touch.phase == TouchPhase.Began)
            {
                isTouch = true;
                if (onDown != null) onDown();
            }
            else if (isTouch && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled))
            {
                isTouch = false;
                if (onUp != null) onUp();
                if (touch.phase == TouchPhase.Ended && onClick != null) onClick();
            }
            else if (!isTouch)
            {
                touch.phase = TouchPhase.Began;
                isTouch = true;
                if (onDown != null) onDown();
            }
        }
        else if (touchTimeout >= 3 && isTouch)
        {
            isTouch = false;
            if (onUp != null) onUp();
        }
        else
        {
            touchTimeout++;
        }
    }
}
